package com.example.animationmodule.pathmeasure

import android.animation.ValueAnimator
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Path
import android.util.AttributeSet
import android.view.View
import android.view.animation.LinearInterpolator


class AnimWaveView @JvmOverloads constructor(
    context: Context, attributeSet:
    AttributeSet? = null, default: Int = 0
) : View(context, attributeSet, default) {
    private val mPath: Path = Path()
    private val mPaint: Paint = Paint().apply {
        color = Color.GREEN
        style = Paint.Style.FILL
    }
    private val mItemWaveLength = 1200
    private var dx = 0

    init {
        startAnim()
    }

    private fun startAnim() {
        val animator = ValueAnimator.ofInt(0, mItemWaveLength)
        animator.duration = 2000
        animator.repeatCount = ValueAnimator.INFINITE
        animator.interpolator = LinearInterpolator()
        animator.addUpdateListener {
            dx = it.animatedValue as Int
            postInvalidate()
        }
        animator.start()
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        mPath.reset()
        val originY = 900
        val halfWaveLen = mItemWaveLength / 2
        mPath.moveTo((-mItemWaveLength + dx).toFloat(), originY.toFloat())
        for (i in -mItemWaveLength..width + mItemWaveLength step mItemWaveLength) {
            mPath.rQuadTo(halfWaveLen / 2.toFloat(), -150f, halfWaveLen.toFloat(), 0F)
            mPath.rQuadTo(halfWaveLen / 2.toFloat(), 150f, halfWaveLen.toFloat(), 0F)

        }
        mPath.lineTo(width.toFloat(), height.toFloat())
        mPath.lineTo(0f,height.toFloat())
        mPath.close()
        canvas.drawPath(mPath, mPaint)

    }

}